package icu.feigroup.infrastructure.adapter.repository;

import icu.feigroup.domain.activity.adapter.repository.IActivityRepository;
import icu.feigroup.domain.activity.model.entity.UserGroupBuyOrderDetailEntity;
import icu.feigroup.domain.activity.model.valobj.*;
import icu.feigroup.infrastructure.dao.*;
import icu.feigroup.infrastructure.dao.po.*;
import icu.feigroup.infrastructure.dcc.DCCService;
import icu.feigroup.infrastructure.redis.IRedisService;
import org.redisson.api.RBitSet;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * projectName:icu.feigroup.infrastructure.adapter.repository
 *
 * @author 飞
 * @since 2025/2/19 17:16
 * description:
 */
@Repository
public class ActivityRepository implements IActivityRepository {
    @Resource
    private GroupActivityMapper groupActivityMapper;
    @Resource
    private GroupDiscountMapper groupDiscountDao;
    @Resource
    private SkuMapper skuMapper;
    @Resource
    private SCSkuActivityMapper scSkuActivityMapper;
    @Resource
    private GroupOrderMapper groupOrderMapper;

    @Resource
    private GroupOrderListMapper groupOrderListMapper;

    @Resource
    private IRedisService redisService;

    @Resource
    private DCCService dccService;


    @Override
    public GroupActivityDiscountVO queryGroupActivityDiscountVO(Long activityId) {
        GroupActivity groupActivityRes = groupActivityMapper.queryValidGroupActivityById(activityId);
        if (groupActivityRes == null) return null;

        String discountId = groupActivityRes.getDiscountId();
        GroupDiscount groupDiscountRes = groupDiscountDao.queryGroupActivityDiscountByDiscountId(discountId);
        if (groupDiscountRes==null) return null;

        GroupActivityDiscountVO.GroupDiscount groupDiscount = GroupActivityDiscountVO.GroupDiscount.builder()
                .discountName(groupDiscountRes.getDiscountName())
                .discountDesc(groupDiscountRes.getDiscountDesc())
                .discountType(DiscountTypeEnum.get(groupDiscountRes.getDiscountType()))
                .marketPlan(groupDiscountRes.getMarketPlan())
                .marketExpr(groupDiscountRes.getMarketExpr())
                .tagId(groupDiscountRes.getTagId())
                .build();

        return GroupActivityDiscountVO.builder()
                .activityId(groupActivityRes.getActivityId())
                .activityName(groupActivityRes.getActivityName())
                .groupDiscount(groupDiscount)
                .groupType(groupActivityRes.getGroupType())
                .takeLimitCount(groupActivityRes.getTakeLimitCount())
                .target(groupActivityRes.getTarget())
                .validTime(groupActivityRes.getValidTime())
                .status(groupActivityRes.getStatus())
                .startTime(groupActivityRes.getStartTime())
                .endTime(groupActivityRes.getEndTime())
                .tagId(groupActivityRes.getTagId())
                .tagScope(groupActivityRes.getTagScope())
                .build();
    }

    @Override
    public SkuVO querySkuByGoodsId(String goodsId) {
        Sku sku = skuMapper.querySkuByGoodsId(goodsId);
        if (sku==null) return null;
        return SkuVO.builder()
                .goodsId(sku.getGoodsId())
                .goodsName(sku.getGoodsName())
                .originalPrice(sku.getOriginalPrice())
                .build();
    }

    @Override
    public SCSkuActivityVO querySCSkuActivityBySCGoodsId(String source, String channel, String goodsId) {
        SCSkuActivity scSkuActivityReq = new SCSkuActivity();
        scSkuActivityReq.setSource(source);
        scSkuActivityReq.setChannel(channel);
        scSkuActivityReq.setGoodsId(goodsId);

        SCSkuActivity scSkuActivity = scSkuActivityMapper.querySCSkuActivityBySCGoodsId(scSkuActivityReq);
        if (scSkuActivity==null) return null;
        return SCSkuActivityVO.builder()
                .source(scSkuActivity.getSource())
                .chanel(scSkuActivity.getChannel())
                .activityId(scSkuActivity.getActivityId())
                .goodsId(scSkuActivity.getChannel())
                .build();
    }

    @Override
    public boolean isTagCrowdRange(String tagId, String userId) {
        RBitSet bitSet = redisService.getBitSet(tagId);
        if (!bitSet.isExists()) return true;
        return bitSet.get(redisService.getIndexFromUserId(userId));
    }

    @Override
    public boolean downgradeSwitch() {
        return dccService.isDowngradeSwitch();
    }

    @Override
    public boolean cutRange(String userId) {
        return dccService.isCutRange(userId);
    }

    @Override
    public List<UserGroupBuyOrderDetailEntity> queryInProgressUserGroupBuyOrderDetailListByOwner(Long activityId, String userId, int ownerCount) {
        // 1. 根据用户ID、活动ID，查询用户参与的拼团队伍
        GroupOrderList groupOrderListReq = new GroupOrderList();
        groupOrderListReq.setActivityId(activityId);
        groupOrderListReq.setUserId(userId);
        groupOrderListReq.setCount(ownerCount);
        List<GroupOrderList> groupOrderLists = groupOrderListMapper.queryInProgressUserGroupBuyOrderDetailListByUserId(groupOrderListReq);
        if (null == groupOrderLists || groupOrderLists.isEmpty()) return null;

        // 2. 过滤队伍获取 TeamId
        Set<String> teamIds = groupOrderLists.stream()
                .map(GroupOrderList::getTeamId)
                .filter(teamId -> teamId != null && !teamId.isEmpty()) // 过滤非空和非空字符串
                .collect(Collectors.toSet());

        // 3. 查询队伍明细，组装Map结构
        List<GroupOrder> groupBuyOrders = groupOrderMapper.queryGroupBuyProgressByTeamIds(teamIds);
        if (null == groupBuyOrders || groupBuyOrders.isEmpty()) return null;

        Map<String, GroupOrder> groupBuyOrderMap = groupBuyOrders.stream()
                .collect(Collectors.toMap(GroupOrder::getTeamId, order -> order));

        // 4. 转换数据
        List<UserGroupBuyOrderDetailEntity> userGroupBuyOrderDetailEntities = new ArrayList<>();
        for (GroupOrderList groupBuyOrderList : groupOrderLists) {
            String teamId = groupBuyOrderList.getTeamId();
            GroupOrder groupBuyOrder = groupBuyOrderMap.get(teamId);
            if (null == groupBuyOrder) continue;

            UserGroupBuyOrderDetailEntity userGroupBuyOrderDetailEntity = UserGroupBuyOrderDetailEntity.builder()
                    .userId(groupBuyOrderList.getUserId())
                    .teamId(groupBuyOrder.getTeamId())
                    .activityId(groupBuyOrder.getActivityId())
                    .targetCount(groupBuyOrder.getTargetCount())
                    .completeCount(groupBuyOrder.getCompleteCount())
                    .lockCount(groupBuyOrder.getLockCount())
                    .validStartTime(groupBuyOrder.getValidStartTime())
                    .validEndTime(groupBuyOrder.getValidEndTime())
                    .outTradeNo(groupBuyOrderList.getOutTradeNo())
                    .build();

            userGroupBuyOrderDetailEntities.add(userGroupBuyOrderDetailEntity);
        }

        return userGroupBuyOrderDetailEntities;
    }

    @Override
    public List<UserGroupBuyOrderDetailEntity> queryInProgressUserGroupBuyOrderDetailListByRandom(Long activityId, String userId, int randomCount) {
        // 1. 根据用户ID、活动ID，查询用户参与的拼团队伍
        GroupOrderList groupOrderListReq = new GroupOrderList();
        groupOrderListReq.setActivityId(activityId);
        groupOrderListReq.setUserId(userId);
        groupOrderListReq.setCount(randomCount * 2); // 查询2倍的量，之后其中 randomCount 数量
        List<GroupOrderList> groupBuyOrderLists = groupOrderListMapper.queryInProgressUserGroupBuyOrderDetailListByRandom(groupOrderListReq);
        if (null == groupBuyOrderLists || groupBuyOrderLists.isEmpty()) return null;

        // 判断总量是否大于 randomCount
        if (groupBuyOrderLists.size() > randomCount) {
            // 随机打乱列表
            Collections.shuffle(groupBuyOrderLists);
            // 获取前 randomCount 个元素
            groupBuyOrderLists = groupBuyOrderLists.subList(0, randomCount);
        }

        // 2. 过滤队伍获取 TeamId
        Set<String> teamIds = groupBuyOrderLists.stream()
                .map(GroupOrderList::getTeamId)
                .filter(teamId -> teamId != null && !teamId.isEmpty()) // 过滤非空和非空字符串
                .collect(Collectors.toSet());

        // 3. 查询队伍明细，组装Map结构
        List<GroupOrder> groupBuyOrders = groupOrderMapper.queryGroupBuyProgressByTeamIds(teamIds);
        if (null == groupBuyOrders || groupBuyOrders.isEmpty()) return null;

        Map<String, GroupOrder> groupBuyOrderMap = groupBuyOrders.stream()
                .collect(Collectors.toMap(GroupOrder::getTeamId, order -> order));

        // 4. 转换数据
        List<UserGroupBuyOrderDetailEntity> userGroupBuyOrderDetailEntities = new ArrayList<>();
        for (GroupOrderList groupBuyOrderList : groupBuyOrderLists) {
            String teamId = groupBuyOrderList.getTeamId();
            GroupOrder groupBuyOrder = groupBuyOrderMap.get(teamId);
            if (null == groupBuyOrder) continue;

            UserGroupBuyOrderDetailEntity userGroupBuyOrderDetailEntity = UserGroupBuyOrderDetailEntity.builder()
                    .userId(groupBuyOrderList.getUserId())
                    .teamId(groupBuyOrder.getTeamId())
                    .activityId(groupBuyOrder.getActivityId())
                    .targetCount(groupBuyOrder.getTargetCount())
                    .completeCount(groupBuyOrder.getCompleteCount())
                    .lockCount(groupBuyOrder.getLockCount())
                    .validStartTime(groupBuyOrder.getValidStartTime())
                    .validEndTime(groupBuyOrder.getValidEndTime())
                    .build();

            userGroupBuyOrderDetailEntities.add(userGroupBuyOrderDetailEntity);
        }

        return userGroupBuyOrderDetailEntities;
    }

    @Override
    public TeamStatisticVO queryTeamStatisticByActivityId(Long activityId) {
        // 1. 根据活动ID查询拼团队伍
        List<GroupOrderList> groupBuyOrderLists = groupOrderListMapper.queryInProgressUserGroupBuyOrderDetailListByActivityId(activityId);

        // 2. 过滤队伍获取 TeamId
        Set<String> teamIds = groupBuyOrderLists.stream()
                .map(GroupOrderList::getTeamId)
                .filter(teamId -> teamId != null && !teamId.isEmpty()) // 过滤非空和非空字符串
                .collect(Collectors.toSet());

        // 3. 统计数据
        Integer allTeamCount = groupOrderMapper.queryAllTeamCount(teamIds);
        Integer allTeamCompleteCount = groupOrderMapper.queryAllTeamCompleteCount(teamIds);
        Integer allTeamUserCount = groupOrderMapper.queryAllUserCount(teamIds);

        // 4. 构建对象
        return TeamStatisticVO.builder()
                .allTeamCount(allTeamCount)
                .allTeamCompleteCount(allTeamCompleteCount)
                .allTeamUserCount(allTeamUserCount)
                .build();
    }
}
